package com.example.minzhengtong.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.example.minzhengtong.Const
import com.example.minzhengtong.HttpRequest
import com.example.minzhengtong.R
import com.example.minzhengtong.base.BaseA
import com.example.minzhengtong.data.UserBean
import com.example.minzhengtong.data.HistoryBean
import com.example.minzhengtong.databinding.ActivityGjjServiceBinding
import com.example.minzhengtong.utils.LogUtil
import com.example.minzhengtong.utils.SpUtil
import com.example.minzhengtong.utils.UIUtils
import com.example.minzhengtong.utils.UIUtils.sp2px
import com.example.minzhengtong.utils.Watermark
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import okhttp3.*
import java.io.IOException
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.jvm.Throws

/**
 * created by WY on 2021/5/28.
 */
class GJJServiceA : BaseA(){

    companion object{
        fun enterThis(context: Context){
            val intent = Intent(context,GJJServiceA::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var binding : ActivityGjjServiceBinding

    private val mData = mutableListOf<HistoryBean.DataBean.ListBean>()
    private val mAdapter by lazy {
        GjjAdapter()
    }

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(0,0)
        binding = ActivityGjjServiceBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setToolBarVisiabale(false)

        ImmersionBar.with(this).statusBarDarkFont(true).navigationBarColor(R.color.white).titleBar(binding.titleBar).init()

        binding.webview.apply {
            setBackgroundColor(0)
            background.alpha = 0
            setOnTouchListener(null)
            setOnClickListener(null)
        }

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(baseContext,LinearLayoutManager.VERTICAL,false)
            adapter = mAdapter
        }

        initListener()

        initTranslate()
        initTime()
        initHint()

    }

    var dollarLeftStr = ""
    var hideLeftStr = "***"
    var dollarRightStr = ""
    var hideRightStr = "***"
    var showStar = true

    var setLeftHideStr = SpannableString("")
    var setRightHideStr = SpannableString("")

    private fun initTranslate(){

        var hideText = ""
        var showText = ""

        if (SpUtil.getInstance().existKey(Const.USER_BEAN)){
            runOnUiThread {
                val bean = SpUtil.getInstance().getObject(Const.USER_BEAN) as UserBean
                bean.apply {
                    Watermark.getInstance().show(baseContext,bean?.data?.lxs,binding?.containerContent)

                    if (data.uzh.length >= 2){
                        val starNum = data.uzh.length-5
                        var starText = ""
                        for (i in 0 until starNum){
                            starText += "*"
                        }
                        if (!data.uname.isNullOrBlank()){
                            hideText = "*${data.uname.substring(1)}（${data.uzh.substring(0,2)}${starText}${data.uzh.subSequence(data.uzh.length-3,data.uzh.length)}）"
                            showText = "${data.uname}（${data.uzh}）"
                        }
                        dollarLeftStr = data.money
                        dollarRightStr = data.y_money
                        binding.dollarLeft.text = dollarLeftStr
                        binding.dollarRight.text = dollarRightStr

                        setLeftHideStr = SpannableString(hideLeftStr)
                        setLeftHideStr.setSpan(StyleSpan(android.graphics.Typeface.BOLD),0,hideLeftStr.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                        setRightHideStr = SpannableString(hideRightStr)
                        setRightHideStr.setSpan(StyleSpan(android.graphics.Typeface.BOLD),0,hideRightStr.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }

                }
                val hideSpannable = SpannableString(hideText)
                val showSpannable = SpannableString(showText)

                hideSpannable.setSpan(StyleSpan(android.graphics.Typeface.BOLD), 0, bean.data.uname.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) //粗体
                hideSpannable.setSpan(AbsoluteSizeSpan(sp2px(11)), bean.data.uname.length, hideText.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
                showSpannable.setSpan(StyleSpan(android.graphics.Typeface.BOLD), 0, bean.data.uname.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) //粗体
                showSpannable.setSpan(AbsoluteSizeSpan(sp2px(11)), bean.data.uname.length, showText.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)

                binding.translate.setImageResource(R.mipmap.img_hide)
                binding.name.text = hideSpannable

                showStar = true

                binding.dollarLeft.text = hideLeftStr
                binding.dollarRight.text = hideRightStr

                binding.translate.setOnClickListener {
                    showStar = !showStar
                    if (!showStar){
                        binding.translate.setImageResource(R.mipmap.img_show)
                        binding.name.text = showSpannable
                        binding.dollarLeft.text = dollarLeftStr
                        binding.dollarRight.text = dollarRightStr
                    }else{
                        binding.translate.setImageResource(R.mipmap.img_hide)
                        binding.name.text = hideSpannable
                        binding.dollarLeft.text = hideLeftStr
                        binding.dollarRight.text = hideRightStr
                    }
                }

            }
        }else{
            HttpRequest().detail(baseContext)
        }

    }

    override fun requestSuccess(json: String) {
        super.requestSuccess(json)
        initTranslate()
    }

    private fun initTime(){
        val calendar = Calendar.getInstance()
        calendar.time = Date()
        calendar.add(Calendar.YEAR,-1)

        binding.start.text = dateFormat.format(calendar.time)
        binding.end.text = dateFormat.format(Date())

        detail(binding.start.text.toString(),binding.end.text.toString())

        binding.start.setOnClickListener {
            val pickerView = TimePickerBuilder(this
            ) { date, v ->
                binding.start.text = getTime(date)
                detail(binding.start.text.toString(),binding.end.text.toString())
            }.build()
            pickerView.show()
        }

        binding.end.setOnClickListener {
            val pickerView = TimePickerBuilder(this
            ) { date, v ->
                binding.end.text = getTime(date)
                detail(binding.start.text.toString(),binding.end.text.toString())
            }.build()
            pickerView.show()
        }

    }

    private fun getTime(date: Date): String? { //可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.time)
        return dateFormat.format(date)
    }

    private fun initHint(){
        val str1 = "若您有厦门公积金账户， 可查看 "
        val str2 = "厦门公职金"
        val spannableString = SpannableString(str1 + str2)
        spannableString.setSpan(ForegroundColorSpan(resources.getColor(R.color.main)),str1.length,(str1 + str2).length,SpannableString.SPAN_EXCLUSIVE_INCLUSIVE)
        binding.hint.text = spannableString
    }

    private fun detail(start : String, end : String){
        mData.clear()

        val formatStart : Date = dateFormat.parse(start)
        val formatEnd : Date = dateFormat.parse(end)
        //开始日期不能大于结束日期或开始结束日期间隔不能超过—年
        val timeSpan = formatEnd.time - formatStart.time
        //val spanLength : Long = 60*1000*60*24*(365+31)
        LogUtil.d("计算时间跨度formatEnd.time=${formatEnd.time},   formatStart.time=${formatStart.time},    timeSpan=${timeSpan}")
        if (timeSpan > (31536000000 /*+ 2678400000*/)){
            binding.recyclerView.visibility = View.GONE
            binding.llSpan.visibility = View.VISIBLE
            binding.placeSpan.visibility = View.VISIBLE
            return
        }else{
            binding.recyclerView.visibility = View.VISIBLE
            binding.llSpan.visibility = View.GONE
            binding.placeSpan.visibility = View.GONE
        }

        val okHttpClient = OkHttpClient()
        val body: RequestBody = FormBody.Builder()
            .add("token", SpUtil.getInstance().getString(Const.TOKEN))
            .add("start", start)
            .add("end", end)
            .build()
        val request = Request.Builder()
            .url(Const.history)
            .post(body)
            .build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
                LogUtil.d("获取明细${e.localizedMessage}")
                UIUtils.showToastSafely("网络连接失败")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val json = response.body()!!.string()
                val bean = Gson().fromJson(json, HistoryBean::class.java)
                if (1 == bean.status){
                    runOnUiThread {
                        binding.start.text = bean.data.start
                        binding.end.text = bean.data.end
                        LogUtil.d("获取列表数据$${bean.data.list.size}$json")
                        val setList = mutableListOf<HistoryBean.DataBean.ListBean>()
                        for (i in bean.data.list.indices){
                            var currentDate = bean.data.list[i].date
                            if (currentDate.contains("-")){
                                currentDate = currentDate.replace("-","")
                            }
                            val currentFormat = SimpleDateFormat("yyyyMMdd")
                            val formatDate : Date = currentFormat.parse(currentDate)
                            LogUtil.d("currentDate=${currentDate}---start=${start}--end=${end}--formatDate > formatEnd=${formatDate > formatEnd}--formatDate < formatStart=${formatDate < formatStart}")
                            if (formatDate > formatEnd){
                                continue
                            }
                            if (formatDate < formatStart){
                                continue
                            }
                            setList.add(bean.data.list[i])
                        }
                        LogUtil.d("筛选后的列表数据为${setList.size}${setList}")
                        mData.addAll(setList)
                        mAdapter.notifyDataSetChanged()
                        if (mData.size == 0){
                            showToast("该时间段内未查询到记录")
                        }
                    }
                }else {
                    UIUtils.showToastSafely(bean.msg)
                }
            }
        })
    }

    private fun initListener(){
        /**
         * 账户信息
         */
        binding.info.setOnClickListener {
            GjjAccountInfoA.enterThis(baseContext)
        }
        /**
         * 公积金提取
         */
        binding.pick.setOnClickListener {
            GJJPickA.enterThis(baseContext)
        }
        /**
         * 还款
         */
        binding.gjjback.setOnClickListener {
            GJJBackA.enterThis(baseContext)
        }
        /**
         * 小闽客服
         */
        binding.kef.setOnClickListener {
            GJJKfA.enterThis(baseContext)
        }
        /**
         * 银行卡
         */
        binding.bank.setOnClickListener {
            GJJBankA.enterThis(baseContext)
        }
        /**
         * 手机号
         */
        binding.mobile.setOnClickListener {
            GJJMobileA.enterThis(baseContext)
        }
        /**
         * 证明打印
         */
        binding.print.setOnClickListener {
            GjjChooseA.enterThis(baseContext)
        }
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0,0)
    }

    inner class GjjAdapter : CommonAdapter<HistoryBean.DataBean.ListBean>(baseContext,R.layout.item_gjj_service,mData){
        override fun convert(holder: ViewHolder, t: HistoryBean.DataBean.ListBean, position: Int) {
            val line = holder.getView<View>(R.id.line)!!
            line.visibility = if (position == mDatas.size-1) View.INVISIBLE else View.VISIBLE
            holder.setText(R.id.title,t.desc/* + t.date.substring(0,t.date.lastIndexOf("-"))*/)
            holder.setText(R.id.time,"记账日期${t.date.replace("-","")}")
            val price = if (t.df_fse.contains("-") || t.df_fse.contains("+")) t.df_fse else "+${t.df_fse}"
            holder.setText(R.id.price,price)
        }
    }

}